<template>
	<div class="home container" id="fullscreen-container" ref="fullscreen">
		<slot name="search"></slot>
		<slot name="menu"></slot>
		<slot name="right"></slot>
		<slot name="bootom"></slot>
		<div id="popup" class="ol-popup">
			<a href="#" id="popup-closer" class="ol-popup-closer"></a>
			<div id="popup-content"></div>
		</div>
		<div class="controlbox">
			<el-tooltip class="item" effect="dark" content="绘制矩形" placement="left-start">
				<i class="juxing" style="color:blue;margin-top: 10px;" @click="juxingHandler"></i>
			</el-tooltip>
			<el-tooltip class="item" effect="dark" content="停止绘制" placement="left-start">
				<i class="stopdraw" style="color:yellowgreen;margin-top: 10px;" @click="endModify"></i>
			</el-tooltip>
			<el-tooltip class="item" effect="dark" content="清楚绘制" placement="left-start">
				<i class="clear" style="color:yellowgreen;margin-top: 10px;" @click="clearHandler"></i>
			</el-tooltip>
		</div>
		<div id="map" :style="{ 'width': mapWidth, 'height': mapHeight }"></div>
		<el-tooltip ref="elTooltip" :append-to-body="false" class="item" effect="light" placement="left">
			<div slot="content">
				<div class="mapbox">
					<li @click="mapChangeHandler('0')" :class="models.active[0] ? 'activeStyle' : ''">
						<img src="../assets/image/dixing.jpg" width="100px" height="50px">
						<div class="on">地形地图</div>
					</li>
					<li @click="mapChangeHandler('1')" :class="models.active[1] ? 'activeStyle' : ''">
						<img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">影像地图</div>
					</li>
					<li @click="mapChangeHandler('2')" :class="models.active[2] ? 'activeStyle' : ''">
						<img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">离线影像</div>
					</li>
				</div>
			</div>
			<div class="map0"></div>
		</el-tooltip>
	</div>
</template>
<script lang="ts">

import GeoJSON from "ol/format/GeoJSON";
import { Component, Vue, Prop, Ref, Emit } from 'vue-property-decorator';
import { Feature, Overlay } from "ol";
import { Point } from "ol/geom";
import EChartsLayer from 'ol-echarts';
import { Modify } from 'ol/interaction';
import { getChart, drawBox, stopDraw, findFeaturesInGeometry, formatArea ,speedStyle,addBlinkingPoint} from '@/utils/map'
import { never } from 'ol/events/condition';

import {
	createMap, mapChangeType,
	createSource,
	createStyle,
	createLayer,
	pointImageStyle,
	createSimpleStyle,
	createStyleDraw,
	createCircleByPolygon,
	

} from '@/utils/map'
@Component({})
export default class WorkMap extends Vue {
	@Ref('fullscreen') private fullscreen!: any;
	@Ref('elTooltip') private elTooltip!: any;
	@Prop()
	propModels: any;
	models: any = {
		map: null,
		mapLanLot: [111.670801, 40.818311],
		geoJsonSource: createSource(),
		active: [true, false, false],
		draw: null,
		modify: null,
		polygonSource: createSource(),
		polygonFeature:null,
		chartLayer: null,
		floodSource: createSource(),
		floodLayer: null,
		polygonInterval: null,
		floodSourceFeature:null,
		inFloodId: null,
		otherFloodId: null,
		isAnimating:false,
	};
	@Prop() private mapWidth!: string;
	@Prop() private mapHeight!: string;
	popupElement: any;
	popupContent: any;
	popupOverlay: any;
	showChart = false;

	initMap() {
		this.models.map = createMap([111.670801, 40.818311]);
		this.models.map.addLayer(createLayer(this.models.geoJsonSource, createStyle("transparent", "darkgreen", "red")));
		this.models.map.addLayer(createLayer(this.models.polygonSource, createStyle("transparent", "green", "red")));
		this.popupElement = document.getElementById('popup');
		this.popupContent = document.getElementById('popup-content');
		this.popupOverlay = new Overlay({
			element: this.popupElement,
			positioning: 'bottom-center',
			stopEvent: false // 阻止地图事件穿透
		});
		this.models.map.addOverlay(this.popupOverlay);
		// 洪水淹没层
		this.models.floodLayer = createLayer(this.models.floodSource, createSimpleStyle('rgba(0, 119, 255, 0.4)'))
		this.models.map.addLayer(this.models.floodLayer);
		this.models.modify = new Modify({
			source: this.models.floodLayer.getSource()!,
			condition: never // 初始禁用
		});
		this.models.map.addInteraction(this.models.modify);
	}

	@Emit('polygonChange')
	polygonAreaHandler(val) {
		return val;
	}

	// 开始绘制createDraw
	startDrawing(type: 'Polygon' | 'LineString') {
		this.clearDrawing();
		this.models.draw = createStyleDraw(this.models.floodSource, type, 'rgba(255, 0, 0, 0.3)', '#ff0000')
	
		this.models.draw.on('drawend', (e) => {
			this.propModels.isDrawing = false;

			const coord = e.feature.getGeometry().getCoordinates() //获取最后点坐标
			if (type === 'Polygon') {
				const area = formatArea(coord);
				this.propModels.area += area;
				//this.polygonAreaHandler(this.models.polygonArea);
			}

		});
		this.models.draw.on('drawend', () => {
			this.propModels.isDrawing = false;
			this.models.map.removeInteraction(this.models.draw!);
		});
		this.propModels.hasWater = true;
		this.models.map.addInteraction(this.models.draw);
		this.propModels.isDrawing = true;
		this.models.modify?.setActive(false);
	}

	createCircleByPolygonHandler(){
		this.models.polygonSource.clear();
		this.models.polygonFeature = null;
		this.models.polygonInterval = null;
		if(this.propModels.radiusKm > 0){
			const radius = createCircleByPolygon(this.models.floodSource.getFeatures()[0].getGeometry(),this.propModels.radiusKm);
			this.models.polygonFeature = radius;
			this.models.polygonSource.addFeature(radius);
			const time = Date.now();
			if(!this.models.polygonInterval){
				this.models.polygonInterval = setInterval(() => {
				if(this.models.polygonFeature){
					this.models.polygonSource.removeFeature(this.models.polygonFeature);
					this.models.polygonFeature.setStyle(speedStyle(time,0.5,'rgba(255, 0, 0, 0.46)','#5b9a8e'));
					this.models.polygonSource.addFeature(this.models.polygonFeature);
				}else{
					clearInterval(this.models.polygonInterval);
				}
			}, 200);
			}
			
		}
	}

	// 清除绘图交互
	clearDrawing() {
		if (this.models.draw) {
			this.models.map.removeInteraction(this.models.draw);
			this.models.draw = null;
		}
		this.propModels.isDrawing = false;
		this.models.modify?.setActive(false);
		this.propModels.hasWater = false;
		if(this.models.polygonInterval){
			clearInterval(this.models.polygonInterval);
		}
		this.models.floodSourceFeature = null;
		this.models.polygonFeature = null;
	}


	// 更新淹没区域（带高程处理）
	updateFloodArea1(waterLevel) {
		const features = this.models.floodLayer.getSource()?.getFeatures();
		if (!features) return;

		features.forEach(feature => {
			feature.setStyle(createStyle(this.getColorByDepth(feature, waterLevel), '#5b9a8e'));
		});
	}




	// 根据水位获取颜色
	getColorByDepth(feature: any, waterLevel): string {
		const baseColor = [0, 119, 255]; // RGB基础颜色
		const depthFactor = Math.min(waterLevel / 50, 1);
		return `rgba(${baseColor.join(',')}, ${0.3 + depthFactor * 0.7})`;
	}

	// 更新淹没区域（简化版算法，实际需结合DEM数据）
	updateFloodArea(waterLevel) {
		const features = this.models.floodLayer.getSource()?.getFeatures();
		if (!features) return;
		let areaV = 0;
		features.forEach(feature => {
			const originalGeometry = feature.getGeometry()?.clone();
			if (!originalGeometry) return;

			// 简单示例：按水位比例放大区域
			const scaledGeometry = originalGeometry.clone();
			scaledGeometry.scale(
				1 + waterLevel / 100,
				1 + waterLevel / 100,
				scaledGeometry.getFirstCoordinate()
			);
			feature.setGeometry(scaledGeometry);
			areaV += formatArea(scaledGeometry.getCoordinates());
		});
		this.propModels.area = areaV;
	}

	private addWaterAnimation() {
		this.models.floodLayer.setStyle(feature => {
			return createSimpleStyle(`rgba(0, 119, 255, ${0.3 + Math.sin(Date.now() / 1000) * 0.2})`)
		});
	}

	// 重置
	private reset() {
		this.models.floodLayer.getSource()?.clear();
		if(this.models.inFloodId){
			cancelAnimationFrame(this.models.inFloodId); 
			this.models.inFloodId = null;
		}
		this.models.isAnimating = false;
		this.models.polygonFeature = null;
		if(this.models.polygonSource){
			this.models.polygonSource.clear();
		}
		
		this.propModels.hasWater = false;
		if(this.models.polygonInterval){
			clearInterval(this.models.polygonInterval);
		}
		this.models.floodSourceFeature = null;
		this.models.polygonFeature = null;

	}

	mapChangeHandler(x) {

		mapChangeType(this.models.map.getLayers(), x, this.models.active);
		this.$message.success("成功切换底图");
	}


	findFeature() {

		const features = this.models.polygonSource.getFeatures();
		if (features.length === 0) {
			this.$message.info("请绘制一个区域");
			return;
		}
		let findF: any = [];
		for (let ft of features) {
			findF = findF.concat(findFeaturesInGeometry(ft.getGeometry(), this.models.geoJsonSource));
		}
		if (findF.length > 0) {
			const m = findF.map((f: any) => f.get("id"));
			return m;
		}
		return [];
	}

	findInFeatures(features) {
		if (features.length === 0) {
			return;
		}
		let findF: any = [];
		features.forEach(ft =>{
			const findC = findFeaturesInGeometry(ft.getGeometry(), this.models.geoJsonSource);
			if(findC && findC.length > 0){
				findF = findF.concat(findC);
			}
		})
		return findF;
		
	}

	findFloodFeatures(){
		const ft = this.models.floodSourceFeature || this.models.floodSource.getFeatures();
		if(!this.models.floodSourceFeature){
			this.models.floodSourceFeature = ft;

		}
		const features =  this.findInFeatures(ft);


		if(features && features.length > 0){
			this.models.inFloodId = addBlinkingPoint(features,'255,0,0',this.models);
			return features.map( f => f.get('id'));
		}
	}

	findOtherFeatures(){
		const floodIn = this.findFloodFeatures();
		
		const ft = this.models.polygonFeature || this.models.polygonSource.getFeatures();
		if(!this.models.polygonFeature){
			this.models.polygonFeature = ft;
		}
	
		let other =  this.findInFeatures([ft]);
		const of =  other.filter(x => {
			return !floodIn.includes(x.get('id'));
		});

		if(of && of.length > 0){
		
			this.models.otherFloodId =  addBlinkingPoint(of,'25, 205, 34',this.models);
			return of.map( f => f.get('id'));
		}
	}


	endModify() {

		stopDraw({
			map: this.models.map,
			draw: this.models.draw,
		});
		this.$message.success("已停止绘制,可以随意操作地图区域");
	}



	clearHandler() {
		this.$confirm('确定要清除已绘制的数据吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			this.endModify();
			this.models.polygonSource.clear();
			if (this.models.chartLayer) {
				this.models.chartLayer.remove();
				this.models.chartLayer = null;
			}
			
			this.reset();
			this.$message.success("已清楚绘制内容");
		});
	}

	buildChartIndex(dataList) {
		// 1. 彻底销毁旧图层（关键修复点）
		if (this.models.chartLayer) {

			this.models.chartLayer.remove();
			this.models.chartLayer = null;
		}
		if (dataList === null || dataList.length === 0) {
			this.$message.info("没有指标数据");
			return;
		}

		// 2. 创建新图层（确保构造函数参数正确）
		const chartOption = getChart('shadow', (params) => {
			return `${params[0].seriesName} ${params[0].name}：${params[0].data.value}`;
		}, dataList.series);

		this.models.chartLayer = new EChartsLayer(chartOption);

		// 3. 安全附加到地图（避免异步问题）
		if (this.models.map) {
			this.models.chartLayer.appendTo(this.models.map);
			//this.models.map.addLayer(this.models.chartLayer);
			// 强制地图重绘（确保图层显示）
			console.log(this.models.chartLayer)
		}
	}

	juxingHandler() {
		this.$message.success("开始绘制矩形区域，在地图区域点击之后移动鼠标即可，如果绘制完成请点击停止绘制按钮");
		this.models.draw = drawBox({
			map: this.models.map,
			draw: this.models.draw,
			source: this.models.polygonSource,
			drawType: 'Circle',
		})
	}

	searchFeature(searchValue) {
		searchValue = searchValue.trim().toLowerCase();
		var features = this.models.geoJsonSource.getFeatures();
		var matchedFeatures: any = [];

		// 清空弹窗
		this.popupOverlay.setPosition(undefined);
		this.popupElement.style.display = 'none';

		// 检索匹配要素
		features.forEach((feature: any) => {
			var propValue = feature.get('name') || '';
			if (propValue.toLowerCase().includes(searchValue) && feature.getGeometry().getType() === 'Point') {
				matchedFeatures.push(feature);
			}
		});

		// 处理结果
		if (matchedFeatures.length > 0) {
			// 显示第一个匹配项的弹窗
			var firstFeature = matchedFeatures[0];
			var geometry = firstFeature.getGeometry();
			var coord = geometry.getCoordinates();
			this.updatePosition(coord);
			// 填充弹窗内容
			this.popupContent.innerHTML = `<h4 sytle="cusor:pointer">${firstFeature.get('name')}</h4>
				<p>坐标: ${coord}</p>`;
			this.popupContent.

				//${firstFeature.get('id')}

				// 定位弹窗并显示
				this.popupOverlay.setPosition(coord);
			this.popupElement.style.display = 'block';

			// 定位地图视图到要素
			this.models.map.getView().fit(geometry.getExtent(), {
				padding: [50, 50, 50, 50],
				duration: 500
			});
		} else {
			this.$message('未找到匹配要素！');
		}
	}

	showData(id) {
		console.log(id);
	}
	setOpacity() {
		this.models.polygonLayer.setStyle(createStyle("transparent", "darkgreen", "red"))
	}

	noOpacity() {
		this.models.polygonLayer.setStyle(createStyle("orange", "darkgreen", "red"))
	}

	mounted() {
		this.initMap();
		this.fullscreen.appendChild(this.elTooltip.popperVM.$el)
	}

	addSource(val) {
		const jsonObj = new GeoJSON().readFeatures(val);
		this.models.geoJsonSource.clear();
		this.models.geoJsonSource.addFeatures(jsonObj);
	}

	updatePosition(val: any) {
		if (val) {
			this.models.map.getView().animate({
				center: val, // 新的中心坐标
				zoom: 16,        // 新的缩放级别
				duration: 3000   // 动画持续时间（毫秒）
			});
		}
		this.setMarker(val);
	}

	setMarker(point) {
		let feature = new Feature({
			geometry: new Point(point),
			style: pointImageStyle('location')
		})
		this.models.geoJsonSource.addFeature(feature);
	}
}
</script>
<style scoped>
.map0 {
	opacity: 0.8;
	width: 24px;
	height: 24px;
	background: url(../assets/image/tooltip.png) center center no-repeat;
	background-size: 16px 16px;
	position: absolute;
	right: 60px;
	top: 10px;
	z-index: 200;
	cursor: pointer;
}

.map1 {
	opacity: 0.5;
	width: 250px;
	height: 40px;
	background: #000 center center no-repeat;
	position: absolute;
	right: 0px;
	top: 0px;
	z-index: 200;
	cursor: pointer;
}

.mapbox {
	width: 320px;
	height: 60px;
	display: flex;
	flex-wrap: nowrap;
	justify-content: space-between;
}

.mapbox li {
	width: 100px;
	height: 50px;
	margin: 5px 0;
	display: block;
	position: relative;
	cursor: pointer;
}

.mapbox li .on {
	height: 16px;
	width: 100px;
	background-color: rgba(0, 0, 0, 0.3);
	color: #fff;
	font-size: 12px;
	position: absolute;
	bottom: 0;
	left: 0;
	display: none;
	text-align: center;
}

.mapbox li:hover .on {
	display: block;
}

.activeStyle {
	width: 100px;
	height: 50px;
	border: 1px solid #f00;
}

.container {
	border: 1px solid #42B983;
	position: relative;
}

.controlbox {
	opacity: 0.8;
	position: absolute;
	z-index: 10000;
	bottom: 200px;
	width: 18px;
	padding: 5px 7px;
	height: 220px;
	right: 20px;
	border: 1px solid #ccc;
	border-radius: 4px;
	cursor: pointer;
	display: flex;
	align-content: space-between;
	flex-direction: column;
	background-color: #fff;
}

.getlength0 {
	width: 18px;
	height: 30px;
	background: url(../assets/image/getnlength.png) center center no-repeat;
	background-size: 16px 16px;
}

.getarea0 {
	width: 18px;
	height: 30px;
	background: url(../assets/image/getarea.png) center center no-repeat;
	background-size: 16px 16px;
}

.ol-popup {
	position: absolute;
	background: white;
	padding: 15px;
	border-radius: 5px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
	min-width: 200px;
	display: none;
	/* 默认隐藏 */
}

.ol-popup:after {
	content: "";
	position: absolute;
	bottom: -10px;
	left: 50%;
	margin-left: -10px;
	border-width: 10px;
	border-style: solid;
	border-color: white transparent transparent transparent;
}

.juxing {
	width: 18px;
	height: 30px;
	background: url(../assets/image/juxing.png) center center no-repeat;
	background-size: 16px 16px;
}

.stopdraw {
	width: 18px;
	height: 30px;
	background: url(../assets/image/stopdraw.png) center center no-repeat;
	background-size: 16px 16px;
}

.clear {
	width: 18px;
	height: 30px;
	background: url(../assets/image/clear.png) center center no-repeat;
	background-size: 16px 16px;
}

.ol-popup-closer {
	position: absolute;
	top: 5px;
	right: 5px;
	width: 20px;
	height: 20px;
	text-decoration: none;
	cursor: pointer;
}

.ol-popup-closer:after {
	content: "✖";
	font-size: 16px;
	color: #999;
}

.ol-popup-closer:hover:after {
	color: #666;
}
</style>
